/**
 * Created by John on 2016/7/15.
 */
var MongoClient = require('mongodb').MongoClient;
var mongo = new MongoClient();
var myDB = null;

mongo.connect('mongodb://localhost/', function (err, db) {
    myDB = db.db('BeginningMongoDB');
    myDB.collection('word_stats', function (err, collection) {
        largeSmallVowels(collection);
        close();
    });
});

function largeSmallVowels(collection) {
    var match = {
        $match: {
            first: {$in: ['a', 'e', 'i', 'o', 'u']}
        }
    };
    var group = {
        $group: {
            _id: '$first',
            largest: {$max: '$size'},
            smallest: {$min: '$size'},
            total: {$sum: 1}
        }
    };
    var sort = {$sort: {first: 1}};

    collection.aggregate([match, group, sort], function (err, items) {
        console.log();
        console.log('Largest and smallest word sizes for words beginning with a vowel');
        displayAggregate(items);
        top5AverageWordFirst(collection);
    });
}

function top5AverageWordFirst(collection) {
    var group = {
        $group: {
            _id: '$first',
            average: {$avg: '$size'}
        }
    };
    var sort = {$sort: {average: -1}};
    var limit = {$limit: 5};

    collection.aggregate([group, sort, limit], function (err, items) {
        console.log();
        console.log("First letter of top 5 largest average word size:")
        displayAggregate(items);
    })
}

function displayAggregate(items) {
    for (var item in items) {
        console.log(items[item]);
    }
}

function close() {
    setTimeout(function () {
        myDB.close();
    }, 3000);
}